package com.zhao.web.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.napp.kaptcha.Kaptcha;
import com.github.napp.kaptcha.KaptchaTextCreator;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;


/** 通用服务
 * @author zhaoyongfei
 *
 */
@Controller
@RequestMapping("common")
public  class CommonController extends BaseController{


	/**
	 * 二维码服务
	 * 
	 * @param content
	 * @param width
	 * @param height
	 * @param response
	 */
	@RequestMapping("qrcode")
	public void qrcode(String content, Integer width, Integer height, HttpServletResponse response) {
		QRCodeWriter writer = new QRCodeWriter();
		BitMatrix bitMatrix = null;
		try {
			bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, ObjectUtils.isEmpty(width) ? 300 : width, ObjectUtils.isEmpty(height) ? 300
					: height);
			BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
			response.setContentType("image/png");
			ImageIO.write(bufferedImage, "png", response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 验证码服务
	 * 
	 * @param response
	 */
	@RequestMapping("captcha")
	public void captcha(HttpServletResponse response) {
		try {
			Kaptcha kaptcha = new Kaptcha();
			BufferedImage bufferedImage = kaptcha.createImage(KaptchaTextCreator.getText(4));
			response.setContentType("image/png");
			ImageIO.write(bufferedImage, "png", response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
